package com.skzh.uavTask.service.impl;

import com.skzh.common.utils.DateUtils;
import com.skzh.common.utils.SecurityUtils;
import com.skzh.uavTask.domain.TaskInfo;
import com.skzh.uavTask.domain.TaskExecRecord;
import com.skzh.uavTask.domain.TaskInfo2;
import com.skzh.uavTask.domain.TaskScheduleVO;
import com.skzh.uavTask.mapper.TaskInfoMapper;
import com.skzh.uavTask.mapper.TaskExecRecordMapper;
import com.skzh.uavTask.service.ITaskInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class TaskInfoServiceImpl implements ITaskInfoService {
    @Autowired
    private TaskInfoMapper taskMapper;

    @Autowired
    private TaskExecRecordMapper taskExecRecordMapper;

    /**
     * 开始执行任务
     *
     * @param taskId 任务ID
     * @return 结果
     */
    @Override
    public int startTask(Long taskId) {
        return startTask(taskId, null);
    }

    /**
     * 开始执行任务
     *
     * @param taskId 任务ID
     * @param operateBy 操作人（如果为null则使用当前登录用户）
     * @return 结果
     */
    public int startTask(Long taskId, String operateBy) {
        // 1. 更新任务状态为"执行中"
        TaskInfo task = new TaskInfo();
        task.setTaskId(taskId);
        task.setStatus("1"); // 执行中
        task.setUpdateBy(operateBy != null ? operateBy : SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateTaskStatus(task);

        // 2. 记录任务开始执行
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setExecTime(DateUtils.getNowDate());
        record.setStatus("0");  // 0表示开始执行
        record.setCreateBy(operateBy != null ? operateBy : SecurityUtils.getUsername());
        record.setCreateTime(DateUtils.getNowDate());
        return taskExecRecordMapper.insertTaskExecRecord(record);
    }

    /**
     * 任务执行完成
     *
     * @param taskId 任务ID
     * @return 结果
     */
    public int completeTask(Long taskId) {
        // 1. 更新任务状态为"已完成"
        TaskInfo task = new TaskInfo();
        task.setTaskId(taskId);
        task.setStatus("2"); // 已完成
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateTaskStatus(task);

        // 2. 记录任务执行完成
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setExecTime(DateUtils.getNowDate());
        record.setStatus("1");  // 1表示执行完成
        record.setCreateBy(SecurityUtils.getUsername());
        record.setCreateTime(DateUtils.getNowDate());
        return taskExecRecordMapper.insertTaskExecRecord(record);
    }

    /**
     * 任务执行失败
     *
     * @param taskId 任务ID
     * @param errorMsg 错误信息
     * @return 结果
     */
    public int failTask(Long taskId, String errorMsg) {
        // 1. 更新任务状态为"执行失败"
        TaskInfo task = new TaskInfo();
        task.setTaskId(taskId);
        task.setStatus("5"); // 执行失败
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        taskMapper.updateTaskStatus(task);

        // 2. 记录任务执行失败
        TaskExecRecord record = new TaskExecRecord();
        record.setTaskId(taskId);
        record.setExecTime(DateUtils.getNowDate());
        record.setStatus("2");  // 2表示执行失败
        record.setErrorMsg(errorMsg);
        record.setCreateBy(SecurityUtils.getUsername());
        record.setCreateTime(DateUtils.getNowDate());
        return taskExecRecordMapper.insertTaskExecRecord(record);
    }

    public List<TaskScheduleVO> getMonthlySchedule(String yearMonth) {
        // 计算开始结束日期
        LocalDate startDate = LocalDate.parse(yearMonth + "-01");
        String targetStart = startDate.format(DateTimeFormatter.ISO_DATE);
        String targetEnd = startDate.withDayOfMonth(startDate.lengthOfMonth()).format(DateTimeFormatter.ISO_DATE);
        List<TaskScheduleVO> taskScheduleVOS = taskMapper.selectMonthlySchedule(yearMonth, targetStart, targetEnd);
        return taskScheduleVOS;
    }

    @Override
    public List<TaskInfo2> selectTaskByDockId(TaskInfo2 taskInfo2) {
        return taskMapper.selectTaskByDockId(taskInfo2);
    }

    @Override
    public List<TaskInfo> selectTaskList(TaskInfo taskInfo) {
        return taskMapper.selectTaskList(taskInfo);
    }

    @Override
    public TaskInfo selectTaskById(Long taskId) {
        return taskMapper.selectTaskById(taskId);
    }

    @Override
    public int insertTask(TaskInfo task) {
        task.setCreateBy(SecurityUtils.getUsername());
        task.setUpdateBy(SecurityUtils.getUsername());
        return taskMapper.insertTask(task);
    }

    @Override
    public int updateTask(TaskInfo task) {
        // 如果没有指定更新人，则使用当前登录用户
        if (task.getUpdateBy() == null || task.getUpdateBy().isEmpty()) {
            task.setUpdateBy(SecurityUtils.getUsername());
        }
        return taskMapper.updateTask(task);
    }

    @Override
    public int deleteTaskByIds(Long[] taskIds) {
        return taskMapper.deleteTaskByIds(taskIds);
    }

    @Override
    public int pauseTask(Long taskId) {
        TaskInfo task = new TaskInfo();
        task.setTaskId(taskId);
        task.setStatus("3"); // 已暂停
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTaskStatus(task);
    }

    @Override
    public int stopTask(Long taskId) {
        TaskInfo task = new TaskInfo();
        task.setTaskId(taskId);
        task.setStatus("4"); // 已终止
        task.setUpdateBy(SecurityUtils.getUsername());
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTaskStatus(task);
    }

    @Override
    public List<TaskExecRecord> selectTaskExecRecordList(Long taskId) {
        return taskExecRecordMapper.selectTaskExecRecordList(taskId);
    }

    @Override
    public int insertTaskExecRecord(TaskExecRecord record) {
        // 如果没有指定创建人，则使用当前登录用户
        if (record.getCreateBy() == null || record.getCreateBy().isEmpty()) {
            record.setCreateBy(SecurityUtils.getUsername());
        }
        record.setPilotName(SecurityUtils.getUsername());
        record.setDeptId(SecurityUtils.getDeptId());
        record.setFlightInfo("飞行信息暂无");
        record.setFlightLocation("飞行地点暂无");

        record.setExecTime(DateUtils.getNowDate());
        record.setCreateTime(DateUtils.getNowDate());
        return taskExecRecordMapper.insertTaskExecRecord(record);
    }
}
